package cn.demomaster.quickui.util;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Build;
import android.os.PersistableBundle;

import androidx.annotation.NonNull;


/**
 * Created by Stardust on 2017/3/10.
 */

public class ClipboardUtil {


    /**
     * 设置粘贴板内容
     *
     * @param context
     * @param text
     */
    //copyContent
    public static void setClip(Context context, CharSequence text) {
        // 获取剪贴板管理器
        ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建剪贴板数据
        ClipData clipData = ClipData.newPlainText(null, text);
        ClipDescription description = clipData.getDescription();
        // 隐私内容：剪切板加密
        PersistableBundle persistableBundle = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            persistableBundle = new PersistableBundle();
        }
        if (Build.VERSION.SDK_INT >= 33) {
            persistableBundle.putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true);
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
                persistableBundle.putBoolean("android.content.extra.IS_SENSITIVE", true);
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            description.setExtras(persistableBundle);
        }
        // 将剪贴板数据设置到剪贴板管理器
        clipboardManager.setPrimaryClip(clipData);
    }

    /**
     * 获取粘贴板内容
     *
     * @param context
     * @return
     */
    public static CharSequence getClip(Context context) {
        ClipData clip = ((ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE)).getPrimaryClip();
        return (clip == null || clip.getItemCount() == 0) ? null : clip.getItemAt(0).getText();
    }

    @NonNull
    public static CharSequence getClipOrEmpty(Context context) {
        CharSequence clip = getClip(context);
        if (clip == null) {
            return "";
        }
        return clip;
    }
}
